#include "test_album.h"

#include <stdlib.h>
#include <stdio.h>
#include <glm/glm.hpp>

static const int dim = 5;

void Print(int *A) {
  int idx = 0;
  for (int i = 0; i < dim; ++i) {
    for (int j = 0; j < dim; ++j) {
      printf("%d ", A[idx++]);
    }
    printf("\n");
  }
  printf("\n");
}

void Transpose(int *A) {
  int *r = A;
  for (int i = 0; i < dim; ++i) {
    int *c = r + dim + i;
    for (int j = i + 1; j < dim; ++j) {
      int tmp = r[j];
      r[j] = c[0];
      c[0] = tmp;
      c += dim;
    }
    r += dim;
  }
}

void TransposeTest() {
  int *A = new int[dim * dim];
  int idx = 0;
  for (int i = 0; i < dim; ++i) {
    for (int j = 0; j < dim; ++j) {
      A[idx++] = rand() % 100; 
    }
  }
  Print(A);  
  Transpose(A);
  Print(A);
}

float get_t(int s, int p, int d, int flag) { 
  int step_ = (rand() % 10) + 1;
  int np = (p / step_) * step_;

  if (0 == d) return 1000;
  if (d > 0) {
    np += step_;
  } else {
    if (np == p) --np;
  }
  return float(np - s) / float(d);
}

using namespace glm;

float march(ivec3 s_xyz, ivec3 pos, ivec3 d_xyz, int flag) {  
  float tx = get_t(s_xyz.x, pos.x, d_xyz.x, flag);
  float ty = get_t(s_xyz.y, pos.y, d_xyz.y, flag);
  float tz = get_t(s_xyz.z, pos.z, d_xyz.z, flag);
  
  float t = tx;
  if (ty < t) t = ty;
  if (tz < t) t = tz;

  return t;
}

void MarchTest() {
  ivec3 e_xyz(rand() % 256, rand() % 256, -(rand() % 128));

  for (int i = 0; i < 1000; ++i) {
    ivec3 s_xyz(rand() % 512, rand() % 512, rand() % 128);
    ivec3 d_xyz = e_xyz - s_xyz;
    ivec3 pos = s_xyz;
    float t = 0;
    while (pos.z >= 0 && pos.z < 128 &&
           pos.x >= 0 && pos.x < 512 && pos.y >= 0 && pos.y < 512) {
      //float tmp = march(s_xyz, pos, d_xyz, 0);      
      double tmp = double(pos.z - 1 - s_xyz.z) / d_xyz.z;
      if (tmp <= t) {
        continue;
      }     
      double tmm_z = tmp * d_xyz.z;
      ivec3 tmp_pos = s_xyz + ivec3(tmp * d_xyz.x, tmp * d_xyz.y, tmp * d_xyz.z);
      if (pos.z - tmp_pos.z < 1) {
        continue;
      }
      t = tmp;
      pos = tmp_pos;
    }
  }
}

namespace ct {
void GeomAlgoTest::Run(int argc, char *argv[]) {
  MarchTest();
}
} // ct

